package cn.bdqn.t354.service.impl;

import cn.bdqn.t354.mapper.LostMapper;
import cn.bdqn.t354.pojo.Chance;
import cn.bdqn.t354.pojo.Customer;
import cn.bdqn.t354.pojo.Lost;
import cn.bdqn.t354.pojo.User;
import cn.bdqn.t354.service.CustomerService;
import cn.bdqn.t354.service.LostService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LostServiceImpl implements LostService {
    @Resource
    private LostMapper lostMapper;
    @Resource
    private CustomerService customerService;

    @Override
    public IPage<Lost> getLostsByPage(String custName, String managerName, String status,
                                      Integer pageNo, Integer pageSize) {
        //组装分页条件
        Page<Lost> page=new Page<>(pageNo,pageSize);
        //组装过滤条件 动态sql
        QueryWrapper<Lost> qw=new QueryWrapper();
        qw.like(custName!=null&&!"".equals(custName), "lst_cust_name",custName);
        qw.like(managerName!=null&&!"".equals(managerName),"lst_cust_manager_name",managerName);
        qw.eq(status!=null&&!"".equals(status),"lst_status",status);
        //客户经理只查自己创建的客户数据
        User user=(User) SecurityUtils.getSubject().getPrincipal();
        if(user.getRole().getRoleId()==2){//客户经理
            qw.eq("lst_cust_manager_id",user.getUsrId());
        }
        //调用分页方法
        IPage<Lost> lostPager=lostMapper.selectPage(page, qw);
        //返回分页对象
        return lostPager;
    }

    @Override
    public Lost getLost(Long id) {
        return lostMapper.selectById(id);
    }

    @Override
    public void updateLost(Lost cstLost) {
        //修改流失预警信息
        lostMapper.updateById(cstLost);
        //如果是确认流失，还需要修改客户的状态为流失状态
        if("3".equals(cstLost.getLstStatus())){
            //根据客户编号，查询客户信息
            Customer customer=customerService.getCustomer(cstLost.getLstCustNo());
            //修改客户的状态
            customer.setCustStatus("2");
            //修改客户状态
            customerService.updateCustomer(customer);
        }
    }
}
